package cn.lexi.vip.aspect.log;

import cn.lexi.vip.controller.IBaseController;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 切点类
 * @Author Aaron
 */
@Aspect
@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class SystemLogAspect implements IBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemLogAspect.class);

    //Controller层切点
    @Pointcut("@annotation(cn.lexi.vip.aspect.log.SystemLogController)")
    public void controllerAspect() {
    }

    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint 切点
     */
    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        try {
            //*========日志开始=========*//
            String methodName = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()";

            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            String methodDescription = method.getAnnotation(SystemLogController.class).description();

            StringBuffer msg = new StringBuffer();
            if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
                //将参数拼成一个字符串
                for (Object object : joinPoint.getArgs()) {
                    msg.append(object + ",");
                }
            }
            //*========日志结束=========*//
            Object object = joinPoint.proceed();
            //*========打印日志=========*//)
            LOGGER.info("请求方法:{},方法描述:{},请求参数:{},请求IP:{},返回参数:{}",
                    methodName, methodDescription, msg.toString(), getIp(), object != null ? object.toString() : "");
            //这里后续还要改成json日志
            return object;
        } catch (Throwable e) {
            LOGGER.error("异常信息:{}", e.getMessage());
            throw e;
        }
    }

}
